package com.btr.ivle.backgroud;

import java.net.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.os.AsyncTask;

import com.btr.ivle.R;
import com.btr.ivle.data.IVLEToken;
import com.btr.ivle.helper.DatabaseWorkbin;
import com.btr.ivle.helper.URLtoString;

public class GetWorkbinTask extends AsyncTask<String, Void, Void>{
	
	private Context context;
	private String WorkbinID;
	
	public GetWorkbinTask(Context context){
		this.context = context;
	}

	protected Void doInBackground(String... texts) {
		WorkbinID = texts[0];

		DatabaseWorkbin dbWorkbin = new DatabaseWorkbin(this.context,IVLEToken.getUserID()+"_Workbin",null,context.getResources().getInteger(R.integer.DBVersion));
		
		try{
        	URL url = new URL("https://ivle.nus.edu.sg/api/Lapi.svc/Workbins?APIKey=" +
        			context.getString(R.string.IVLE_API_KEY) + "&AuthToken=" + IVLEToken.getToken() + "&WorkbinID="
        				+ WorkbinID + "&Duration=0&TitleOnly=false");
        	
        	JSONObject jObject = new JSONObject(URLtoString.get(url));
	        JSONArray resultsArrary = jObject.getJSONArray("Results").getJSONObject(0).getJSONArray("Folders");
	        
	        getFolder(resultsArrary, dbWorkbin, null);
	        
	        dbWorkbin.getReadableDatabase().close();
	        dbWorkbin.close();
  
        }catch(Exception ex){
	    }
		return null;
	}
	
	private boolean getFolder(JSONArray Folders ,DatabaseWorkbin dbWorkbin, String ParentID) throws JSONException{
		String table = IVLEToken.getUserID() + "_Workbin";
		ContentValues values;
		String ID, FolderName, OpenDate, CloseDate;
		boolean AllowUpload, allDownloaded = true;
		
		for (int i = 0; i < Folders.length(); i++) {
        	ID = Folders.getJSONObject(i).getString("ID").toString();
        	FolderName = Folders.getJSONObject(i).getString("FolderName").toString();
        	OpenDate = Folders.getJSONObject(i).getString("OpenDate").toString().substring(6, 19);
        	CloseDate = Folders.getJSONObject(i).getString("CloseDate").toString().substring(6, 19);
        	AllowUpload = Folders.getJSONObject(i).getBoolean("AllowUpload");
        	
        	values = new  ContentValues();
        	values.put(dbWorkbin.ID, ID);
        	values.put(dbWorkbin.FolderName, FolderName);
        	values.put(dbWorkbin.OpenDate, OpenDate);
        	values.put(dbWorkbin.CloseDate, CloseDate);
        	values.put(dbWorkbin.AllowUpload, AllowUpload);
        	values.put(dbWorkbin.ParentID, ParentID);
        	values.put(dbWorkbin.isFile, false);
        	values.put(dbWorkbin.WorkbinID, WorkbinID);
        	//dbWorkbin.getReadableDatabase().replace(table, null, values);
        	
        	JSONArray subFolders = Folders.getJSONObject(i).getJSONArray("Folders");
        	if(subFolders.length()>0)
        		if(!getFolder(subFolders, dbWorkbin, ID))
        			allDownloaded = false;
        	
        	JSONArray Files = Folders.getJSONObject(i).getJSONArray("Files");
        	if(Files.length()>0)
        		if(!getFiles(Files, dbWorkbin, ID))
        			allDownloaded = false;
        		
        	values.put(dbWorkbin.isDownloaded, allDownloaded);
        	dbWorkbin.getReadableDatabase().replace(table, null, values);
		}
		
		return allDownloaded;
	}
	
	private boolean getFiles(JSONArray Files ,DatabaseWorkbin dbWorkbin, String ParentID) throws JSONException{
		String table = IVLEToken.getUserID() + "_Workbin";
		ContentValues values;
		String ID, FileName, FileType, UploadTime;
		long FileSize;
		boolean isDownloaded, allDownloaded = true;
		
		for (int i = 0; i < Files.length(); i++) {
        	ID = Files.getJSONObject(i).getString("ID").toString();
        	FileName = Files.getJSONObject(i).getString("FileName").toString();
        	FileSize = Files.getJSONObject(i).getLong("FileSize");
        	FileType = Files.getJSONObject(i).getString("FileType").toString();
        	isDownloaded = Files.getJSONObject(i).getBoolean("isDownloaded");
        	if(!isDownloaded)
        		allDownloaded = false;
        	UploadTime = Files.getJSONObject(i).getString("UploadTime").toString().substring(6, 19);
        	
        	values = new  ContentValues();
        	values.put(dbWorkbin.ID, ID);
        	values.put(dbWorkbin.FileName, FileName);
        	values.put(dbWorkbin.FileSize, FileSize);
        	values.put(dbWorkbin.FileType, FileType);
        	values.put(dbWorkbin.isDownloaded, isDownloaded);
        	values.put(dbWorkbin.UploadTime, UploadTime);
        	values.put(dbWorkbin.ParentID, ParentID);
        	values.put(dbWorkbin.isFile, true);
        	values.put(dbWorkbin.WorkbinID, WorkbinID);
        	dbWorkbin.getReadableDatabase().replace(table, null, values);
		}
		
		return allDownloaded;
	}
	
    protected void onPostExecute(Void result) {
    	@SuppressWarnings("unchecked")
		AsyncTaskCompleteListener<String> l = (AsyncTaskCompleteListener<String>) context;
    	l.onAsyncTaskComplete(""); 
    }
}
